<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/1/29
 * Time: 14:56
 */

namespace App\HttpController\Admin;


use App\Model\FormIdModel;
use App\Model\RecordsModel;
use App\Model\TmplmsgsModel;
use App\Utility\MiniProgram;
use App\Utility\RedisTools;
use Carbon\Carbon;

class TemplateMsgController extends AuthController
{

    /**
     * 获取 模板消息_列表
     */
    public function index(){
        try{
            $wechat = new MiniProgram();
            $list = $wechat->getTemplateList();
            $tmplmsgsModel = new TmplmsgsModel();
            foreach ($list as &$item){
                $content = explode('}}', $item['content']);
                $keyword = array();
                $keywordText = [];
                foreach ($content as $val) {
                    $keyword[] = trim(substr($val, strpos($val, "{{") + 2, -5));
                    $keywordText[] = trim(substr($val, 0, strpos($val, "{{")));
                }
                $form = [];
                //获取数据库对应关键词的值，进行填充返回
                $keywordForDB = $tmplmsgsModel->where('template_id', $item['template_id'])->first();
                if (!$keywordForDB) {
                    //模板ID不存在，创建
                    foreach ($keyword as $word) {
                        if ($word) {
                            $form[$word] = '';
                        }
                    }
                    $item['page'] = '';
                    $item['emphasis'] = '';
                    $createData = [
                        'template_id' => $item['template_id'],
                        'keyword' => [$form],
                        'page' => $item['page'],
                        'title' => $item['title'],
                        'emphasis' => $item['emphasis'],
                    ];
                    $tmplmsgsModel->create($createData);
                } else {
                    $form = $keywordForDB['keyword'];
                    $item['page'] = $keywordForDB['page'];
                    $item['emphasis'] = $keywordForDB['emphasis'];
                }
                $item['form'] = $form;
                $item['keyword'] = array_filter($keyword);
                $item['keyword_text_arr'] = array_combine($item['keyword'], array_filter($keywordText));
                $item['keyword_text'] = implode(',', array_filter($keywordText));
            }
            //查询formid相关（总数，总可用数，今日可用数，今日新增数）
            $formModel = new FormIdModel();
            //删除已过期的
            $formModel->clear();
            return $this->writeJson(0,$list);
        }catch (\Exception $e){
            return $this->writeJson(1,null, $e->getMessage());
        }
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            $model = new TmplmsgsModel();
            $msg = $model->where('template_id', $data['template_id'])->first();
            if (!$data['template_id'] || !$msg) {
                return $this->writeJson(1,null,'数据不存在');
            }
            $data['id'] = $msg['id'];
            $model->update($data);
            return $this->writeJson(0, null, '更新成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 推送
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function push(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $model = new TmplmsgsModel();
        $msg = $model->where('template_id', $data['id'])->first();
        if (!$data['id'] || !$msg) {
            return $this->writeJson(1,null,'数据不存在');
        }
        $recordModel = new RecordsModel();
        //生成推送记录
        $insert = [
            'template_id' => $data['id'],
            'title' => $msg['title'],
        ];
        $recordModel->create($insert);
        //开启任务-创建模板消息推送队列
        $queue = new RedisTools('message-create');
        $queue->lPush($data['id']);
        return $this->writeJson(0, null, '推送成功');
    }

    // 重置token
    public function token(){
        $wechat = new MiniProgram();
        $token = $wechat->getToken(true);
        return $this->writeJson(0, $token, '重置access_token成功');
    }
}
